var jspapi;
var $el;
var extensionPlugin;
var setting={
    verticalGutter 	: 0,
    autoReinitialise   : true
};

var surplusCount = 0;//加载量--用于分页加载通话记录数据
var loadPage = 0;//加载页数

layui.use(['form','layer','laydate','table','laytpl','element'],function(){
    var element = layui.element;
    var laydate = layui.laydate;
    var form = layui.form,
        // layer = parent.layer === undefined ? layui.layer : top.layer,
        layer=layui.layer;
    $ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.table;
});

$(function(){
    // the element we want to apply the jScrollPane
    /**
      {
            verticalGutter 	: 0,
            stickToBottom     : true,//滑到底部
            autoReinitialise :true
            showArrows - boolean (default false)//显示滑杆两边的箭头
            maintainPosition - boolean (default true)//保持原位置
            stickToBottom- boolean (default false)//滑到底部
            stickToRight- boolean (default false)//滑到最右边
            autoReinitialise - boolean (default false)//自动加载出现滑杆
            autoReinitialiseDelay - int (default 500)//自动加载的时间延迟
            verticalDragMinHeight - int (default 0)//垂直拖拽的最小高度
            verticalDragMaxHeight - int (default 99999)//处置拖拽的最大高度
            horizontalDragMinWidth - int (default 0)//水平拖拽的长度
            horizontalDragMaxWidth - int (default 99999)//水平拖拽的最大长度
            contentWidth - int (default undefined)//内幕内用的宽度
            animateScroll - boolean (default false)//滚动动画
            animateDuration - int (default 300)//动画延迟
            animateEase - string (default 'linear')//动画轨迹
            hijackInternalLinks - boolean (default false)//截获内部链接
            verticalGutter - int (default 4)//处置不掉长度
            horizontalGutter - int (default 4)//水平不掉长度
            mouseWheelSpeed - int (default 10)//鼠标疼速度
            arrowButtonSpeed - int (default 10)//方向键按钮的速度
            arrowRepeatFreq - int (default 100)//按钮事件重复频率
            arrowScrollOnHover - boolean (default false)//接手鼠标在方向键上滑过的动作
            verticalArrowPositions - string [split|before|after|os] (default split)//垂直方向上按钮的位置
            horizontalArrowPositions - string [split|before|after|os] (default split)//水平方向上按钮的位置
            enableKeyboardNavigation - boolean (default true)//是否接受键盘操作
            hideFocus - boolean (default false)//隐藏焦点
            clickOnTrack - boolean (default true)//路径上点击操作
            trackClickSpeed - int (default 30)//互动轨迹上的点击速度
            trackClickRepeatFreq - int (default 100)//滑动轨迹上的重复频率
    }*/

     $el= $('#jp-container').jScrollPane(setting);
        // the extension functions and options
        extensionPlugin 	= {
            extPluginOpts	: {
                // speed for the fadeOut animation
                mouseLeaveFadeSpeed	: 500,
                // scrollbar fades out after hovertimeout_t milliseconds
                hovertimeout_t		: 1000,
                // if set to false, the scrollbar will be shown on mouseenter and hidden on mouseleave
                // if set to true, the same will happen, but the scrollbar will be also hidden on mouseenter after "hovertimeout_t" ms
                // also, it will be shown when we start to scroll and hidden when stopping
                useTimeout			: true,
                // the extension only applies for devices with width > deviceWidth
                deviceWidth			: 980
            },
            hovertimeout	: null, // timeout to hide the scrollbar
            isScrollbarHover: false,// true if the mouse is over the scrollbar
            elementtimeout	: null,	// avoids showing the scrollbar when moving from inside the element to outside, passing over the scrollbar
            isScrolling		: true,// true if scrolling
            addHoverFunc	: function() {
                // run only if the window has a width bigger than deviceWidth
                if( $(window).width() <= this.extPluginOpts.deviceWidth ) return false;
                var instance		= this;
                // functions to show / hide the scrollbar
                $.fn.jspmouseenter 	= $.fn.show;
                $.fn.jspmouseleave 	= $.fn.fadeOut;
                // hide the jScrollPane vertical bar
                var $vBar			= this.getContentPane().siblings('.jspVerticalBar').hide();
                /*
                 * mouseenter / mouseleave events on the main element
                 * also scrollstart / scrollstop - @James Padolsey : http://james.padolsey.com/javascript/special-scroll-events-for-jquery/
                 */
                $el.bind('mouseenter.jsp',function() {
                    // show the scrollbar
                    $vBar.stop( true, true ).jspmouseenter();
                    if( !instance.extPluginOpts.useTimeout ) return false;
                    // hide the scrollbar after hovertimeout_t ms
                    clearTimeout( instance.hovertimeout );
                    instance.hovertimeout 	= setTimeout(function() {
                        // if scrolling at the moment don't hide it
                        if( !instance.isScrolling )
                            $vBar.stop( true, true ).jspmouseleave( instance.extPluginOpts.mouseLeaveFadeSpeed || 0 );
                    }, instance.extPluginOpts.hovertimeout_t );
                }).bind('mouseleave.jsp',function() {
                    // hide the scrollbar
                    if( !instance.extPluginOpts.useTimeout )
                        $vBar.stop( true, true ).jspmouseleave( instance.extPluginOpts.mouseLeaveFadeSpeed || 0 );
                    else {
                        clearTimeout( instance.elementtimeout );
                        if( !instance.isScrolling )
                            $vBar.stop( true, true ).jspmouseleave( instance.extPluginOpts.mouseLeaveFadeSpeed || 0 );
                    }
                });

                if( this.extPluginOpts.useTimeout ) {

                    $el.bind('scrollstart.jsp', function() {

                        // when scrolling show the scrollbar
                        clearTimeout( instance.hovertimeout );
                        instance.isScrolling	= true;
                        $vBar.stop( true, true ).jspmouseenter();

                    }).bind('scrollstop.jsp', function() {

                        // when stop scrolling hide the scrollbar (if not hovering it at the moment)
                        clearTimeout( instance.hovertimeout );
                        instance.isScrolling	= false;
                        instance.hovertimeout 	= setTimeout(function() {
                            if( !instance.isScrollbarHover )
                                $vBar.stop( true, true ).jspmouseleave( instance.extPluginOpts.mouseLeaveFadeSpeed || 0 );
                        }, instance.extPluginOpts.hovertimeout_t );

                    });

                    // wrap the scrollbar
                    // we need this to be able to add the mouseenter / mouseleave events to the scrollbar
                    var $vBarWrapper	= $('<div/>').css({
                        position	: 'absolute',
                        left		: $vBar.css('left'),
                        top			: $vBar.css('top'),
                        right		: $vBar.css('right'),
                        bottom		: $vBar.css('bottom'),
                        width		: $vBar.width(),
                        height		: $vBar.height()
                    }).bind('mouseenter.jsp',function() {

                        clearTimeout( instance.hovertimeout );
                        clearTimeout( instance.elementtimeout );

                        instance.isScrollbarHover	= true;

                        // show the scrollbar after 100 ms.
                        // avoids showing the scrollbar when moving from inside the element to outside, passing over the scrollbar
                        instance.elementtimeout	= setTimeout(function() {
                            $vBar.stop( true, true ).jspmouseenter();
                        }, 100 );

                    }).bind('mouseleave.jsp',function() {

                        // hide the scrollbar after hovertimeout_t
                        clearTimeout( instance.hovertimeout );
                        instance.isScrollbarHover	= false;
                        instance.hovertimeout = setTimeout(function() {
                            // if scrolling at the moment don't hide it
                            if( !instance.isScrolling )
                                $vBar.stop( true, true ).jspmouseleave( instance.extPluginOpts.mouseLeaveFadeSpeed || 0 );
                        }, instance.extPluginOpts.hovertimeout_t );

                    });

                    $vBar.wrap( $vBarWrapper );
                }
            }
        };
        jspapi= $el.data('jsp');
    // extend the jScollPane by merging
    $.extend(true, jspapi, extensionPlugin);
    jspapi.addHoverFunc();
    if(sessionId!=null && sessionId!=undefined && sessionId!="" && fromPage=="callDetailPage"){ //判断是查看call客通话详情时，再加载通话信息
        if(commitTo!=null && commitTo!=undefined && commitTo == 'ASR_ALIYUN'){
            var robotId = "robot_1";
            if(firstSpeaking!=undefined && firstSpeaking!="" && firstSpeaking!=null){
                getRobotAnswer(firstSpeaking,robotId);
            }
        }
        ajaxLoadCallText(sessionId);
    }
    // ajaxLoadCallText("AWboCca8o3xXEI7uhKhv_92356"); //调样式时使用
});


/**
 * 下载录音文件
 * @param url
 * @param createUserId
 */
function down(obj){
    var url = $(obj).attr("url");
    var sessionId = $(obj).attr("sessionId");
    console.log(url);
    console.log(sessionId);
    var $eleForm ;
    if(url.indexOf("aliyun")>0){
        $eleForm = $("<a href='"+url+"' download='"+sessionId+".wav'></a>");
    }else{
        $eleForm = $("<a href='"+url+"' download=''></a>");
    }
    $(document.body).append($eleForm);
    //提交表单，实现下载
    $eleForm[0].click();
}


function getSaleAnswer(content, id) {
    console.log("=======getSaleAnswer====");
    var imgUrl = baseUrl + "/images/callDetail/sale.png"; // /images/11.jpg
    var objStr = '<div  id="' + id + '" class="talk_recordbox">\n' +
        '                        <div class="user"><img class="header-icon" src="' + imgUrl + '" />经纪</div>\n' +
        '                        <div class="talk_recordtextbg">&nbsp;</div>\n' +
        '                        <div class="talk_recordtext">\n' +
        '                            <h3>' + content + '</h3>\n' +
        '                        </div>\n' +
        '                    </div>' +
        '<div class="clear"></div>';
    $(".jspPane").append(objStr);
    //重新加载刷新滚动条
    jspapi.reinitialise();
    jspapi.scrollToBottom();
}

function getRecommendAnswer(content) {
    var objStr = '<div class="tip_msg_recordboxme" >' +
        '<div class="talk_msg_recordtext" >' +
        '<span>' + content + '</span>' +
        '</div></div>' +
        '<div class="clear"></div>';
    $(".jspPane").append(objStr);
    //重新加载刷新滚动条
    jspapi.reinitialise();
    jspapi.scrollToBottom();
}


function getRobotAnswer(content, id) {
    console.log("=======getRobotAnswer====");
    var imgUrl = baseUrl + "/images/callDetail/robot.png"; // /images/11.jpg
    var objStr = '<div  id="' + id + '" class="talk_recordbox">\n' +
        '                        <div class="user"><img class="header-icon" src="' + imgUrl + '" />萝卜仔</div>\n' +
        '                        <div class="talk_recordtextbg">&nbsp;</div>\n' +
        '                        <div class="talk_recordtext">\n' +
        '                            <h3>' + content + '</h3>\n' +
        '                        </div>\n' +
        '                        <div  class="tip_recordboxme">\n' +
        '                             <span class="keyword_span" style="padding: 5px">\n' +
        '                             </span>\n' +
        '                        </div>' +
        '                    </div>' +
        '<div class="clear"></div>';
    $(".jspPane").append(objStr);
    //重新加载刷新滚动条
    jspapi.reinitialise();
    jspapi.scrollToBottom();
}

function getCustomerAnswer(content, id) {
    console.log("=======getCustomerAnswer====");
    var imgUrl = baseUrl + "/images/callDetail/customer.png";
    var objStr = '<div id="' + id + '" class="talk_recordboxme">\n' +
        '                        <div class="user"><img class="header-icon" src="' + imgUrl + '" />客户</div>\n' +
        '                        <div class="talk_recordtextbg">&nbsp;</div>\n' +
        '                        <div class="talk_recordtext">\n' +
        '                            <h3>' + content + '</h3>\n' +
        '                        </div>\n' +
        '                       <div  class="tip_recordboxme">\n' +
        '                             <span class="keyword_span" style="padding: 5px">\n' +
        '                             </span>\n' +
        '                        </div>' +
        '                    </div>' +
        '<div class="clear"></div>';

    $(".jspPane").append(objStr);
    //重新加载刷新滚动条
    jspapi.reinitialise();
    jspapi.scrollToBottom();
}


function  loadCallText(mapList) {
    if(mapList!=null && mapList!=undefined && mapList.length>0){
        for(var i=0;i<mapList.length;i++){
            console.log(mapList[i]);
            var content = mapList[i].context;
            var id = mapList[i].id;
            if(mapList[i].textType == "CUSTOMER_SPEAKING"){//客户说的
                getCustomerAnswer(content,id);
                if(mapList[i].recommendText!=undefined && mapList[i].recommendText!=null && mapList[i].recommendText!=""){
                    if(commitTo!=null && commitTo!=undefined && commitTo == 'ASR_ALIYUN'){
                        var robotId = "robot"+mapList[i].id;
                        getRobotAnswer(mapList[i].recommendText,robotId);
                        if(mapList[i].action == 'hangup'){
                            $("#" + id + " .tip_recordboxme .keyword_span").html("触发挂机操作，通话结束。");
                        }
                    }else{
                        getRecommendAnswer("推荐话术："+mapList[i].recommendText);
                    }

                    if((mapList[i].knowledgeBaseId!=""&& mapList[i].knowledgeBaseId!=null) || (mapList[i].currentFlowStepId!="" && mapList[i].currentFlowStepId!=null)){//如是匹配到 情况下， 才显示
                        var matchKeyWords = mapList[i].keyworlds;
                        var matchValue = mapList[i].intention;
                        var matchType = (mapList[i].knowledgeBaseId!=""&& mapList[i].knowledgeBaseId!=null)?"知识库":((mapList[i].currentFlowStepId!=""&& mapList[i].currentFlowStepId!=null)?"分支":"");
                        if(matchType!="" && matchValue!=""){
                            var val = "匹配到" + matchType + ":" + "【" + matchValue + "】";
                            if(matchType == "无"){
                                val = "未匹配到问题/回答分支，待学习";
                            }
                            if(matchKeyWords!=""){
                                val += ",关键词：" + matchKeyWords;
                            }
                            $("#" + id + " .tip_recordboxme .keyword_span").html(val);
                        }
                    }
                }
            }else if(mapList[i].textType == "USER_SPEAKING"){//经纪说的
                getSaleAnswer(content,id);
            }
        }
    }
}


function ajaxLoadCallText(sessionId) {
    loadPage++;
    $.ajax({
        type: "POST",
        url:  baseUrl+'/linkageCall/loadCallText?loadPage='+loadPage+"&sessionId="+sessionId,
        dataType: 'json',
        success: function (data) {
            console.log(data);
            if(data.code<=0){
                parent.layer.msg("获取通话内容"+data.msg);
            }else{
                loadCallText(data.records);
                if(data.records!=null && data.records.length>0){
                    surplusCount = data.total - data.records.length;
                    if(surplusCount>0){
                        ajaxLoadCallText(sessionId);
                    }else{
                        jspapi.reinitialise();
                        jspapi.scrollToY(0,0);
                    }
                }
            }
        },
        error: function () {
            parent.layer.msg("获取通话内容异常");
            return ;
        }
    });
}


